package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news_website_db/models"
	"path/filepath"
	"strings"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	name := c.GetString("name")
	address := c.GetString("address")
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "请选择要上传的文件",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "文件过大",
		}
		c.ServeJSON()
		return
	}
	ext := map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if ext[suffix] == false {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "文件格式不正确",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	var news models.New
	news.Title = title
	news.Name = name
	news.Address = address
	news.Img = "http://127.0.0.1:8080/" + path
	if news.Add() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "上传失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "上传成功",
	}
	c.ServeJSON()
	return
}
func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	var news models.New
	news.ID = uint(id)
	if news.Del() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
